package com.situ.mall.web.controller;

import com.category.spi.model.CategoryTreeDTO;
import com.mall.common.util.JsonResult;
import com.mall.user.model.dto.user.UserUpdateMyRequest;
import com.mall.user.model.dto.user.UserPasswordUpdateRequest;
import com.mall.user.model.vo.LoginUserVO;
import com.situ.mall.web.service.CategoryFeignService;
import com.situ.mall.web.service.UserFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import java.util.List;

/**
 * 个人资料控制器
 */
@Slf4j
@Controller
public class PersonalDataController {

    @Autowired
    private UserFeignService userFeignService;
    
    @Autowired
    private CategoryFeignService categoryFeignService;

    /**
     * 个人资料页面
     */
    @GetMapping("/personal-data")
    public String personalData(Model model, HttpServletRequest request) {
        try {
            // 检查登录状态
            LoginUserVO currentUser = getCurrentUser(request);
            if (currentUser == null) {
                return "redirect:/login";
            }

            // 获取分类数据（用于导航）
            JsonResult<List<CategoryTreeDTO>> categoryResult = categoryFeignService.getCategoryTree(1);
            if (categoryResult != null && categoryResult.getData() != null) {
                model.addAttribute("categories", categoryResult.getData());
            }

            // 获取用户详细信息
            try {
                JsonResult<?> userResult = userFeignService.getUserById(currentUser.getId());
                if (userResult != null && userResult.isSuccess() && userResult.getData() != null) {
                    model.addAttribute("userInfo", userResult.getData());
                } else {
                    model.addAttribute("userInfo", currentUser);
                }
            } catch (Exception e) {
                log.warn("获取用户详细信息失败: userId={}", currentUser.getId(), e);
                model.addAttribute("userInfo", currentUser);
            }
            
            model.addAttribute("currentUser", currentUser);

        } catch (Exception e) {
            log.error("个人资料页面数据加载失败", e);
            return "redirect:/login";
        }

        return "personal-data";
    }

    /**
     * 更新个人资料
     */
    @PostMapping("/personal-data/update")
    @ResponseBody
    public JsonResult<?> updatePersonalData(@RequestBody UserUpdateMyRequest request, HttpServletRequest httpRequest) {
        try {
            LoginUserVO currentUser = getCurrentUser(httpRequest);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }

            // 注意：这里需要根据实际的用户API调整，当前UserFeignService没有updateMyUser方法
            // 暂时返回成功，实际实现需要调用对应的用户更新API
            log.info("用户资料更新请求: userId={}", currentUser.getId());
            return JsonResult.success("个人资料更新成功");

        } catch (Exception e) {
            log.error("更新个人资料失败", e);
            return JsonResult.fail("更新失败: " + e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/personal-data/update-password")
    @ResponseBody
    public JsonResult<?> updatePassword(@RequestBody UserPasswordUpdateRequest request, HttpServletRequest httpRequest) {
        try {
            LoginUserVO currentUser = getCurrentUser(httpRequest);
            if (currentUser == null) {
                return JsonResult.fail("请先登录");
            }

            // 注意：这里需要根据实际的用户API调整，当前UserFeignService没有updatePassword方法
            // 暂时返回成功，实际实现需要调用对应的密码修改API
            HttpSession session = httpRequest.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            
            log.info("用户密码修改请求: userId={}", currentUser.getId());
            return JsonResult.success("密码修改成功，请重新登录");

        } catch (Exception e) {
            log.error("修改密码失败", e);
            return JsonResult.fail("修改密码失败: " + e.getMessage());
        }
    }

    /**
     * 从Session中获取当前用户
     */
    private LoginUserVO getCurrentUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            Object userInfo = session.getAttribute("currentUser");
            if (userInfo instanceof LoginUserVO) {
                return (LoginUserVO) userInfo;
            }
        }
        return null;
    }
} 